package com.example.demo.Interceptor;

import com.example.demo.constant.Constant;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.nio.charset.StandardCharsets;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("方法执行前面");
        HttpSession session=request.getSession(false);
        if(session==null||!StringUtils.hasLength((String) session.getAttribute(Constant.USER_NAME))){
            response.setStatus(401);
            response.setContentType("text/html;charset=utf-8");
            response.getOutputStream().write("用户未进行登录".getBytes(StandardCharsets.UTF_8));
            return false;
        }
        return true;
    }

}
